package com.huitone.smspfm.context.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Pattern;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

import com.bin.common.utils.ArrayUtils;
import com.bin.common.utils.StringUtils;

public class ContextPropertiesUtils2 extends PropertyPlaceholderConfigurer {
	
	private static Logger logger = LogManager.getLogger(ContextPropertiesUtils2.class);
	
	private static Map<String,String> propertyMap = new HashMap<String, String>();
	
	private static List<String> confpaths = new ArrayList<>();
	
	@Override
	public void setLocations(Resource... locations) {
		
		String property = System.getProperty("tmp.properties");
		if (!StringUtils.isEmpty(property)) {
			Resource resource = new FileSystemResource(property);
			locations = (Resource[]) ArrayUtils.add(locations, resource);
		}
		
		super.setLocations(locations);
		
		if (locations != null) {
			for (Resource location:locations) {
				try {
					String parent = location.getFile().getParent();
					confpaths.add(parent);
					logger.debug(location);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	@Override
	protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props)
			throws BeansException {
		super.processProperties(beanFactoryToProcess, props);
        for (Object key : props.keySet()) {
            String keyStr = StringUtils.objToString(key.toString()).trim();
            String value = StringUtils.objToString(props.getProperty(keyStr)).trim();
            propertyMap.put(keyStr, value);
        }
	}
	
	/**
	 * 重新加载配置文件信息
	 * @param cfgfile
	 */
	public synchronized static void reload(String cfgfile) {
		
		for (int i = 0 ; i < confpaths.size() ; i ++) {
			File file = new File(confpaths.get(i));
			if (file.exists() && file.isFile()) {
				Properties props = new Properties();
				try {
					props.load(new FileInputStream(file));
				} catch (IOException e) {}
				Set<Object> keySet = props.keySet();
				for (Object key : keySet) {
		            String keyStr = StringUtils.toString(key).trim();
		            String value = StringUtils.toString(props.getProperty(keyStr)).trim();
		            propertyMap.put(keyStr, value);
		        }
			}
		}
		
		if(!StringUtils.isEmpty(cfgfile)) {
			File file = new File(cfgfile);
			if (file.exists() && file.isFile()) {
				Properties props = new Properties();
				try {
					props.load(new FileInputStream(file));
				} catch (IOException e) {}
				Set<Object> keySet = props.keySet();
				for (Object key : keySet) {
		            String keyStr = StringUtils.toString(key).trim();
		            String value = StringUtils.toString(props.getProperty(keyStr)).trim();
		            propertyMap.put(keyStr, value);
		        }
			}
		}
	}
	
	public synchronized static String getProperty(String name) {
		
		if (propertyMap == null) return null;
		
        return StringUtils.toString(propertyMap.get(name));
    }
	
	public synchronized static List<String> getPropertys(String regex) {
		
		if (propertyMap == null) return null;
		
		List<String> resultList = new ArrayList<>();
		
		List<String> keyList = new ArrayList<>();
		
		Iterator<String> iterator = propertyMap.keySet().iterator();
		
		while(iterator.hasNext()) {
			String next = iterator.next();
			if (Pattern.compile(regex).matcher(next).matches()) {
				keyList.add(next);
			}
		}
		
		Collections.sort(keyList);
		
		for (String key:keyList) {
			resultList.add(propertyMap.get(key));
		}
		
		return resultList;
	}
}
